package com.wondertek.poms.core.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.wondertek.oes.sso.client.service.sso.SsoRemoteService;
import com.wondertek.oes.sso.common.model.resp.Info;
import com.wondertek.poms.common.constant.Constants;
import com.wondertek.poms.common.service.impl.ServiceImpl;
import com.wondertek.poms.common.utils.StringUtil;
import com.wondertek.poms.common.vo.GlobalCodeEnum;
import com.wondertek.poms.common.vo.ResultBean;
import com.wondertek.poms.core.config.MsgConfig;
import com.wondertek.poms.core.filter.RuleFilterChain;
import com.wondertek.poms.core.filter.impl.*;
import com.wondertek.poms.core.service.IImageService;
import com.wondertek.poms.core.service.IPcProductRuleService;
import com.wondertek.poms.core.service.IPrdContService;
import com.wondertek.poms.core.service.ISystemConfigService;
import com.wondertek.poms.core.utils.HttpClientUtil;
import com.wondertek.poms.core.utils.OutHttpUtil;
import com.wondertek.poms.dao.bo.PrdContBo;
import com.wondertek.poms.dao.po.*;
import com.wondertek.poms.dao.po.es.ContentVo;
import com.wondertek.poms.dao.pojo.*;
import com.wondertek.poms.dao.repo.*;
import com.wondertek.poms.dao.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.transaction.Transactional;
import java.io.File;
import java.io.IOException;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author chenjijiang
 * @description
 */
@Slf4j
@Service
@Scope("prototype")
public class PrdContServiceImpl extends ServiceImpl<PrdCont, Long> implements IPrdContService {
    @Resource
    private IPrdContDao prdContDao;
    @Resource
    private IPrdInfoDao prdInfoDao;
    @Resource
    private IContentDao contentDao;
    @Resource
    private IProductInfoPackageDao productInfoPackageDao;

    @Resource
    private IEmergencyBcLogDao emergencyBcLogDao;

    @Autowired
    private IPcProductRuleService pcProductRuleService;
    @Autowired
    private SsoRemoteService ssoRemoteService;
    @Autowired
    private ISystemConfigService systemConfigService;
    @Autowired
    private IImageService imageService;

    @Autowired
    private OutHttpUtil outHttpUtil;
    @PersistenceContext
    public EntityManager entityManager;

    @Resource
    private MsgConfig msgConfig;
    //加密
    static final String ALGORITHM = "DES";
    /**
     * 算法名称/加密模式/填充方式
     **/
    static final String CIPHER_ALGORITHM = "DES/ECB/PKCS5Padding";

    /**
     * 密钥，getBytes的长度必须大于等于8
     **/
    static final String SECRET_KEY = "gansufensheng20171116";

    @Override
    public PrdCont deleteLogic(Long id) {
        return null;
    }

    @Override
    public PrdCont merge(PrdCont model) {
        return null;
    }

    /*/**
     * @Author MrYuan
     * @Date: 2021/2/18 17:49
     * @Description: 节目发布记录列表查询实现
     * @params:  [entity, page, rows, sord, sidx]
     * @return: org.springframework.data.domain.Page<com.wondertek.poms.dao.pojo.ProgramPojo>
     */
    @Override
    public Page<ProgramPojo> findAll(ProgramPojo entity, int page, int rows, String sord, String sidx) {
		StringBuffer condition = sqlStringWhere(entity, sord, sidx);
		Object o = entityManager
				.createNativeQuery("select count(*) from ( " + condition.toString() + " ) a").getSingleResult();
		int count = Convert.toInt(o);
		Pageable pageable = getPageable(page - 1, rows, sord, sidx);

		if (count > 0) {
			Query query = entityManager.createNativeQuery(condition.toString());
			query.setFirstResult(pageable.getPageNumber() * pageable.getPageSize());
			query.setMaxResults(pageable.getPageSize());
			List<Object[]> resultList = query.getResultList();
			List<ProgramPojo> list = getList(resultList);
			PageImpl<ProgramPojo> result = new PageImpl<>(list, pageable, count);
			entityManager.close();
			return result;
		}
		entityManager.close();
		return Page.empty(pageable);
    }
	public StringBuffer sqlStringWhere(ProgramPojo entity, String sidx, String sord) {
		StringBuffer condition = new StringBuffer();
		String sql = "SELECT b.PRD_CONT_ID,b.CONTENT_ID,c.NAME ,b.BC_PERSON,i.NAME bokongfang,b.BC_TIME,b.BC_STATUS\n" +
				"FROM BC_LOG b,BC_INFO i,CONTENT c,BC_TIME_LOG t,PRD_INFO p\n" +
				"WHERE b.BC_ID= i.BC_ID\n" +
				"AND i.BC_ID=t.BC_ID\n" +
				"AND t.CONTENT_ID=c.CONTENT_ID\n" +
				"AND p.BC_ID=i.BC_ID ";
		condition.append(sql);
		if (!ObjectUtils.isEmpty(entity)) {
			if (entity.getPrdContId() != 0) {
				condition.append("AND b.PRD_CONT_ID= '" + entity.getPrdContId() + "' ");
			}
//			if (entity.getContentId() != 0) {
//				condition.append("AND b.CONTENT_ID= '" + entity.getContentId() + "' ");
//			}
//			if (StrUtil.isNotBlank(entity.getBcName())) {
//				condition.append("AND i.NAME LIKE '%" + entity.getBcName() + "%' ");
//			}
//			if (StrUtil.isNotBlank(entity.getBcPerson())) {
//				condition.append("AND b.BC_PERSON LIKE '%" + entity.getBcPerson() + "%' ");
//			}
//			if (entity.getBcStatus() != 0) {
//				condition.append("AND b.BC_STATUS=" + entity.getBcStatus());
//			}
//			if (StrUtil.isNotBlank(entity.getPrdName())) {
//				condition.append("AND c.DISPLAY_NAME LIKE '%" + entity.getDisplayName() + "%'");
//			}
//			if (StrUtil.isNotBlank(entity.getPrdName())) {
//				condition.append("AND p.NAME  LIKE '%" + entity.getPrdName() + "%'");
//			}
//			if (StrUtil.isNotBlank(entity.getPubhStart())) {
//				condition.append("AND b.BC_TIME>='" + entity.getPubhStart() + "' ");
//			}
//			if (StrUtil.isNotBlank(entity.getPubhEnd())) {
//				condition.append("AND b.BC_TIME<='" + entity.getPubhEnd() + "' ");
//			}
		}
		condition.append("order by " + sidx + " " + sord);
		return condition;
	}
	private List<ProgramPojo> getList(List<Object[]> resultList) {
		List<ProgramPojo> list = new ArrayList<>();
		for (Object[] obj : resultList) {
            ProgramPojo pojo = new ProgramPojo();
			pojo.setPrdContId(Convert.toLong(obj[0]));
//			pojo.setContentId(Convert.toInt(obj[1]));
//			pojo.setContentName(Convert.toStr(obj[2]));
//			pojo.setBcName(Convert.toStr(obj[3]));
//			pojo.setBcPerson(Convert.toStr(obj[4]));
//			pojo.setBcTime(Convert.toStr(obj[5]));
//			pojo.setBcStatus(Convert.toInt(obj[6]));
			list.add(pojo);
		}
		return list;
	}
    /**
     * <p><b>Title:</b> passProductRule </p>
     * <p><b>Description:</b> 判断二级产品的规则是否符合;
     * 限制入包条件：限制规则存在，并且符合限制规则；或者限制规则不存在；然后已选规则存在，且不符合已选规则；反之结束流程
     * </p>
     *
     * @param vo
     * @param productId
     * @return true 表示没通过
     * @author douzi
     */
    @Override
    public boolean passProductRule(Content vo, Long productId) {
        Map<Integer, List<PcProductRule>> prsMap = getProductRuleMap(productId);
        List<PcProductRule> limitRules = prsMap.get(Constants.RULE_TYPE_2);
        if (CollectionUtil.isNotEmpty(limitRules)) {
            log.info("二级产品规则|业务数据：" + vo.getContentId() + "|媒资ID:" + vo.getAssetId() + "|入包二级产品:" + productId + "|限制规则数量:" + limitRules.size());
            if (isMatchLimitRule(vo, limitRules)) {
                return true;
            }
        }

        List<PcProductRule> selectRules = prsMap.get(Constants.RULE_TYPE_1);
        if (selectRules == null) {
            return false;
        }
        log.info("二级产品规则|业务数据：" + vo.getContentId() + "|媒资ID:" + vo.getAssetId() + "|入包二级产品:" + productId + "|已选规则数量:" + selectRules.size());
        return !isMatchSelectRule(vo, selectRules);
    }


    public Map<Integer, List<PcProductRule>> getProductRuleMap(Long secondId) {
        List<PcProductRule> prs = pcProductRuleService.findRuleBySecondId(secondId);
        Map<Integer, List<PcProductRule>> map = new HashMap<>();
        prs.forEach(r -> {
            List<PcProductRule> partPrs = null;
            if (!map.containsKey(r.getRuleType())) {
                partPrs = new ArrayList<>();
            } else {
                partPrs = map.get(Integer.parseInt(r.getRuleType()));
            }

            if (Integer.parseInt(r.getRuleType()) == Constants.RULE_TYPE_1 || Integer.parseInt(r.getRuleType()) == Constants.RULE_TYPE_2) {
                partPrs.add(r);
                map.put(Integer.parseInt(r.getRuleType()), partPrs);
            }
        });

        return map;
    }

    /**
     * <p><b>Title:</b> isMatchLimitRule</p>
     * <p><b>Description:</b> 是否匹配二级产品限制规则</p>
     *
     * @param vo
     * @param limitRules
     * @return
     * @author douzi
     */
    private boolean isMatchLimitRule(Content vo, List<PcProductRule> limitRules) {
        boolean isMatch = false;

        for (PcProductRule limitRule : limitRules) {
            isMatch = contentFilter(limitRule, vo, true);
            if (isMatch) {
                break;
            }
        }
        return isMatch;
    }

    /**
     * <p><b>Title:</b> isMatchSelectRule</p>
     * <p><b>Description:</b> 是否匹配二级产品已选规则</p>
     *
     * @param vo
     * @param selectRules
     * @return
     * @author douzi
     */
    private boolean isMatchSelectRule(Content vo, List<PcProductRule> selectRules) {
        boolean isMatch = false;

        for (PcProductRule selectRule : selectRules) {
            isMatch = contentFilter(selectRule, vo, false);
            if (isMatch) {
                break;
            }
        }
        return isMatch;
    }

    /**
     * <p><b>Title:</b> contentFilter</p>
     * <p><b>Description:</b> 二级产品规则过滤</p>
     *
     * @param rule    二级产品规则
     * @param vo      接收的内容vo
     * @param isLimit 是否是限制规则
     * @return
     * @author douzi
     */
    public boolean contentFilter(PcProductRule rule, Content vo, boolean isLimit) {
        RuleFilterChain rfc = new RuleFilterChain();

        if (isLimit) {
            rfc.addFilter(new CopyRightBlackAreaFilter());
        } else {
            rfc.addFilter(new CopyRightWhiteAreaFilter());
        }
        rfc.addFilter(new CopyRightCpIdFilter())
                .addFilter(new CopyRightTerminalFilter())
                .addFilter(new CopyRightScopeFilter())
                .addFilter(new CopyRightTypeFilter())
                .addFilter(new AuthorizationWayFilter())
                .addFilter(new NeedDRMFilter())
                .doFilter(rule, vo, rfc);

        if (rfc.isFlag()) {
            log.info("二级产品规则|业务数据：" + vo.getContentId() + "|assetId:" + vo.getAssetId() + "|二级产品ID:" + rule.getProductInfoPackageId() + "| 符合" + (isLimit ? "二级产品限制规则" : "二级产品已选规则") + "|" + rule.toString());
        } else {
            log.info("二级产品规则|业务数据：" + vo.getContentId() + "|assetId:" + vo.getAssetId() + "|二级产品ID:" + rule.getProductInfoPackageId() + "| 不符合" + (isLimit ? "二级产品限制规则" : "二级产品已选规则") + "|" + rfc.getResultStr().toString());
        }
        return rfc.isFlag();
    }

    @Override
    public List<PrdCont> getPrdContByMmsId(String assetId) {
        return prdContDao.getPrdContByAssetId(Long.parseLong(assetId));
    }

    @Override
    public List<PrdCont> getPrdContByMmsId(String assetId, Long productInfoPackageId) {
        return prdContDao.getPrdContByMmsId(Long.parseLong(assetId), productInfoPackageId);
    }

    @Override
    public List<PrdCont> getPrdContByMmsIdInPrdInfo(String assetId, Long prdInfoId) {
        return prdContDao.getPrdContByMmsIdInPrdInfo(Long.parseLong(assetId), prdInfoId);
    }

    @Override
    public List<PrdCont> getSerialsAllPublish(Long prdInfoId, Long mssId) {
        return prdContDao.getSerialsAllPublish(prdInfoId, mssId);
    }

    @Override
    public List<PrdCont> findPcByContentId(String liveContentId, Long productInfoPackageId) {
        return prdContDao.findPcByContentId(liveContentId, productInfoPackageId);
    }

    @Override
    public List<ProductContentPojo> getbcListByPrdContId(Long prdContId, Long bcId) {
        List<ProductContentPojo> pcs = this.getContentPojo(prdContId, bcId);
        if (pcs != null && pcs.size() > 0) {
            for (ProductContentPojo pc : pcs) {
                String cId = pc.getContentid();
                String userName = pc.getBcperson();
                try {
                    Long userId = Long.valueOf(pc.getBcperson());
                    if (userId != 0) {
                        Info allUserInfo = ssoRemoteService.getAllUserInfo();
                        List<String> users = allUserInfo.getUsers();
                        for (String user : users) {
                            //字符串为 用户id=用户名
                            String[] arr = user.split("=");
                            if (userId.equals(arr[0])) {
                                userName = arr[1];
                            }
                        }
                    }
                    pc.setBcperson(userName);
                } catch (NumberFormatException e) {
                    // do nothing
                }

                List<SecondclassifyPojo> scs = this.getSecondclassifysByContentId(cId);
                List<MediaFilePojo> mfs = this.getMediaFilesByContentId(cId);

                pc.setSecondclassify(scs == null ? new ArrayList<SecondclassifyPojo>() : scs);
                pc.setMediafile(mfs == null ? new ArrayList<MediaFilePojo>() : mfs);

                // displayPath
                String preViewImageUrl = outHttpUtil.findByKey("PreViewImageUrl");

                List<String> df = new ArrayList<String>();
                String preImgPath = outHttpUtil.findByKey("BC_IMAGE_BROWER_PATH");
                if (StringUtil.isBlank(preImgPath)) {
                    preImgPath = "/poms_publish/cmvideo/image";
                }
                preImgPath = preImgPath + "/" + cId.substring(0, 4) + "/"
                        + cId.substring(4, 7) + "/" + cId.substring(7) + "/"; // [/poms_publish/cmvideo/image/4/3/3/]

                File imgDir = new File(preImgPath);
                if (imgDir.exists() && imgDir.isDirectory()) {
                    File[] imgFiles = imgDir.listFiles();
                    if (imgFiles != null && imgFiles.length > 0) {
                        for (File img : imgFiles) {
                            if (img.exists() && img.isFile()) {
                                int index = img.getAbsolutePath().indexOf("image");
                                if (index != -1) {
                                    df.add(preViewImageUrl + img.getAbsolutePath().substring(index));
                                }
                            }
                        }
                    }
                }
                pc.setDisplayfile(df);
            }
        }
        return pcs;
    }

    /**
     * <p><b>Title:</b> getSecondclassifysByContentId</p>
     * <p><b>Description:</b> 获取二级分类</p>
     *
     * @param cId
     * @return
     * @author douzi
     */
    private List<SecondclassifyPojo> getSecondclassifysByContentId(String cId) {
        StringBuffer sql = new StringBuffer();
        sql.append("SELECT sc.classify_key, listagg(sc.classify_value,',') within GROUP (order by sc.classify_value) classify_value FROM second_classify sc");
        sql.append(" WHERE sc.content_id =" + cId);
        sql.append(" GROUP BY sc.content_id, sc.classify_key ");
        Query query = entityManager.createNativeQuery(sql.toString());
        List<Object[]> resultList = query.getResultList();
        List<SecondclassifyPojo> list = getSecondclassifysList(resultList);
        entityManager.close();
        return null;
    }

    private List<SecondclassifyPojo> getSecondclassifysList(List<Object[]> resultList) {
        List<SecondclassifyPojo> result = new ArrayList<SecondclassifyPojo>();
        for (Object[] obj : resultList) {
            SecondclassifyPojo sc = new SecondclassifyPojo();
            sc.setClassifykey(StringUtil.nullToString(obj[0]));
            sc.setClassifyvalue(StringUtil.nullToString(obj[1]));

            result.add(sc);
        }
        return result;
    }

    /**
     * <p><b>Title:</b> getMediaFilesByContentId</p>
     * <p><b>Description:</b> 获取媒体文件</p>
     *
     * @param contentId
     * @return
     * @author douzi
     */
    @SuppressWarnings("unchecked")
    private List<MediaFilePojo> getMediaFilesByContentId(String contentId) {
        StringBuffer sql = new StringBuffer();
        sql.append(" SELECT m.media_file_id,           ");
        sql.append("        m.media_file_name,         ");
        sql.append("        m.media_code_rate,         ");
        sql.append("        m.media_type,              ");
        sql.append("        m.media_resolution,        ");
        sql.append("        m.media_file_preview_path, ");
        sql.append("        m.media_usage_code         ");
        sql.append("   FROM media_file m               ");
        sql.append("  WHERE m.content_id =" + contentId);

        Query query = entityManager.createNativeQuery(sql.toString());
        List<Object[]> resultList = query.getResultList();
        List<MediaFilePojo> list = getMediaFileList(resultList);
        entityManager.close();
        return list;
    }

    private List<MediaFilePojo> getMediaFileList(List<Object[]> resultList) {
        List<MediaFilePojo> result = new ArrayList<MediaFilePojo>();
        for (Object[] obj : resultList) {
            MediaFilePojo m = new MediaFilePojo();
            m.setMediafileid(StringUtil.nullToString(obj[0]));
            m.setMediafilename(StringUtil.nullToString(obj[1]));
            m.setMediacodereate(StringUtil.nullToString(obj[2]));
            m.setMediatype(StringUtil.nullToString(obj[3]));
            m.setMediaresolution(StringUtil.nullToString(obj[4]));
            m.setMediafilepreviewpath(StringUtil.nullToString(obj[5]));
            m.setMediausagecode(StringUtil.nullToString(obj[6]));
            result.add(m);
        }
        return result;
    }

    @SuppressWarnings("unchecked")
    public List<ProductContentPojo> getContentPojo(Long prdContId, Long bcId) {
        StringBuilder condition = sqlStringWhere(prdContId);
        Query query = entityManager.createNativeQuery(condition.toString());
        List<Object[]> resultList = query.getResultList();
        List<ProductContentPojo> list = getList(resultList, bcId);
        entityManager.close();
        return list;
    }

    private List<ProductContentPojo> getList(List<Object[]> rows, Long bcId) {
        List<ProductContentPojo> list = new ArrayList<>();
        for (Object[] obj : rows) {
            int i = -1;
            ProductContentPojo p = new ProductContentPojo();
            p.setPrdcontid(StringUtil.nullToLong(obj[++i]));
            p.setPrdinfoid(StringUtil.nullToLong(obj[++i]));
            p.setPrdinfoname(StringUtil.nullToString(obj[++i]));
            p.setContentid(StringUtil.nullToString(obj[++i]));
            p.setAssetid(StringUtil.nullToString(obj[++i]));
            p.setContentname(StringUtil.nullToString(obj[++i]));
            p.setShortname(StringUtil.nullToString(obj[++i]));
            p.setDetail(StringUtil.nullToString(obj[++i]));
            p.setCduration(StringUtil.nullToLong(obj[++i]));

            p.setBcid(StringUtil.nullToString(bcId));

            p.setCpid(StringUtil.nullToString(obj[++i]));
            p.setNcpid(StringUtil.nullToString(obj[++i]));
            p.setCopyrightcpid(StringUtil.nullToString(obj[++i]));
            p.setPrimarykeyword(StringUtil.nullToString(obj[++i]));
            p.setKeywords(StringUtil.nullToString(obj[++i]));
            p.setFeetype(StringUtil.nullToString(obj[++i]));
            p.setCreatetime(StringUtil.nullToString(obj[++i]));
            p.setStatus(StringUtil.nullToLong(obj[++i]));
            p.setContenttype(StringUtil.nullToString(obj[++i]));
            p.setFormtype(StringUtil.nullToString(obj[++i]));
            p.setCategory(StringUtil.nullToString(obj[++i]));
            p.setLabels(StringUtil.nullToString(obj[++i]));
            p.setCreatorid(StringUtil.nullToString(obj[++i]));
            p.setDirectrecflag(StringUtil.nullToString(obj[++i]));
            p.setMedialevel(StringUtil.nullToString(obj[++i]));
            p.setAuthor(StringUtil.nullToString(obj[++i]));
            p.setSerialcount(StringUtil.nullToString(obj[++i]));
            p.setSerialsequence(StringUtil.nullToString(obj[++i]));
            p.setSerialcontentid(StringUtil.nullToString(obj[++i]));
            p.setLastmodifytime(StringUtil.nullToString(obj[++i]));
            p.setWatermask(StringUtil.nullToString(obj[++i]));
            p.setAssist(StringUtil.nullToString(obj[++i]));
            p.setDisplaytype(StringUtil.nullToString(obj[++i]));
            p.setDisplayname(StringUtil.nullToString(obj[++i]));
            p.setUdid(StringUtil.nullToString(obj[++i]));
            p.setBcstatus(StringUtil.nullToString(obj[++i]));
            p.setBcperson(StringUtil.nullToString(obj[++i]));
            Object bcTime = obj[++i];
            p.setBctime(bcTime == null ? "" : DateUtil.formatDateTime(StringUtil.nullToDate(bcTime.toString(), "yyyy-MM-dd HH:mm:ss")));
            p.setBcrefusereason(StringUtil.nullToString(obj[++i]));
            p.setRepealstatus(StringUtil.nullToString(obj[++i]));
            String repStatus = p.getRepealstatus();
            String isPub = "0";
            if (repStatus.equals("12") || repStatus.equals("20") || repStatus.equals("21") || repStatus.equals("23")) {
                isPub = "1";
            }
            p.setPubstatus(isPub);
            //updateFields 去重  by wwk
            String updateFields = StringUtil.null2Str(obj[++i]);
            String[] arrayUpdateFields = updateFields.split(",");
            String jupdateFields = "";
            if (arrayUpdateFields.length == 1) {
                jupdateFields = updateFields;
            } else {
                for (String updateField : arrayUpdateFields) {
                    if (!jupdateFields.contains(updateField)) {
                        jupdateFields = jupdateFields + "," + updateField;
                    }
                }
            }
            if (jupdateFields.startsWith(",")) {
                jupdateFields = jupdateFields.substring(1);
            }

            p.setUpdateFields(jupdateFields);
            p.setBcPriority(StringUtil.null2Str(obj[++i]));
            p.setDistStatus(StringUtil.null2Str(obj[++i]));
            p.setPubNewStatus(StringUtil.null2Str(obj[++i]));
            p.setIsDelete(StringUtil.null2Str(obj[++i]));
            p.setSerialTrailingSequence(StringUtil.null2Str(obj[++i]));
            list.add(p);
        }
        return list;
    }

    private StringBuilder sqlStringWhere(Long prdContId) {
        StringBuilder sql = new StringBuilder();
        sql.append(" SELECT pc.prd_cont_id,                     "); // 节目编号
        sql.append("        pi.prdinfoid,                       "); // 产品包编号
        sql.append("        pi.name pi_name,                    "); // 产品包名称
        sql.append("        c.content_id,                       "); // 内容编号
        sql.append("        c.asset_id,                         "); // 媒资编号
        sql.append("        c.name c_name,                      "); // 内容名称
        sql.append("        c.short_name,                       "); // 内容简称
        sql.append("        c.detail,                           "); // 内容说明
        sql.append("        c.cduration,                        "); // 播放时长
        //sql.append("        pi.bc_id,                           "); // 播控方标识
        sql.append("        c.cp_id,                            "); // 合作伙伴编号
        sql.append("        c.n_cpid,                           "); // CP编号
        sql.append("        c.copyright_cpid,                   "); // 所属CP
        sql.append("        c.primary_key_word,                 "); // 主关键字
        sql.append("        c.key_words,                        "); // 关键字
        sql.append("        c.fee_type,                         "); // 收费类型 枚举值：1-免费；2-收费
        sql.append("        c.create_time,                      "); // 生成时间
        sql.append("        c.status,                           "); // 状态
        sql.append("        c.type,                             "); // 服务类型
        sql.append("        c.form_type,                        "); // 剧集类型
        sql.append("        c.category,                         "); // 内容类别
        sql.append("        c.labels,                           "); // 标签
        sql.append("        c.creator_id,                       "); // 操作员编号
        sql.append("        c.direct_rec_flag,                  "); // 支持直播回放
        sql.append("        c.media_level,                      "); // 媒体文件清晰度
        sql.append("        c.author,                           "); // 内容作者
        sql.append("        c.serial_count,                     "); // 剧集的总集数
        sql.append("        c.serial_sequence,                  "); // 单集在剧集中序号
        sql.append("        c.serial_content_id,                "); // 单集所属剧集的内容ID
        sql.append("        c.last_modify_time,                 "); // 最后修改时间
        sql.append("        c.water_mask,                       "); // 水印
        sql.append("        c.assist,                           "); // 辅助分类信息
        sql.append("        c.display_type,                     "); // 内容一级分类ID
        sql.append("        c.display_name,                     "); // 内容一级分类名称
        sql.append("        c.udid,                             "); // 自定义内容标识
        sql.append("        pc.bc_status,                       "); // 播控状态
        sql.append("        pc.bc_person,                       "); // 播控人
        sql.append("        pc.bc_time,                         "); // 播控时间
        sql.append("        pc.bc_refuse_reason,                "); // 播控拒绝原因
        sql.append("        pc.pub_status,                      "); // oms发布状态 10 11 12...
        sql.append("        c.update_fields,                    ");    // 变更字段信息
        sql.append("        c.bc_priority,                      ");    // 播控优先级
        sql.append("        pc.dist_status,                     ");    // 分发状态
        sql.append("        pc.publish_no_voms_status,          ");    // 发布状态
        sql.append("        pc.is_delete,           			");    // 删除状态 0-未删除， 1-变更不符合进包规则删除， 2-手动删除， 4-相同媒资内容替换删除
        sql.append("        c.serial_trailing_sequence          ");    // 预告片在剧集中的序号
        sql.append("   FROM prd_info pi, prd_cont pc, content c ");
        sql.append("  WHERE 1 = 1            					");
        sql.append("    AND pi.prdinfoid = pc.prd_info_id       ");
        sql.append("    AND pc.content_id = c.content_id        ");
        sql.append("    AND pc.prd_cont_Id =" + prdContId);
        return sql;
    }

    @Override
    public List<PrdCont> findPcByContentIdInPrdInfo(String liveContentId, Long prdInfoId) {
        return prdContDao.findPcByContentIdInPrdInfo(liveContentId, prdInfoId);
    }

    @Override
    public List<ContentVo> getListByLike(Map<String, Object> map,
                                         Integer start, Integer limit, Long prdInfoId) {
        List<Object> params = new ArrayList<Object>();
        StringBuffer sqlQuery = new StringBuffer("");
        sqlQuery.append(" select pc.PRD_CONT_ID, pc.CONTENT_ID, c.NAME, c.CDURATION, c.copyright_cpid, c.KEY_WORDS, c.DISPLAY_TYPE, c.SCOPE, c.COPYRIGHT_TYPE, c.FEE_TYPE, ");
        sqlQuery.append("        pc.BC_STATUS, pc.DIST_STATUS, pc.PUB_STATUS, c.CREATE_TIME, c.ID, c.STATUS, c.CATEGORY, c.ASSET_ID, pc.BC_REFUSE_REASON, c.FORM_TYPE,     ");
        sqlQuery.append("        pc.IS_EMERGENCY, c.CDN_STATUS, c.GSLB_STATUS, c.TYPE, pc.PUBLISH_NO_VOMS_STATUS, c.MOVIE_LIB_ID, pc.PRD_INFO_ID, pc.PRICE, pc.sal_price,  ");
        sqlQuery.append("        c.DETAIL, c.CACHE_CDN_STATUS, c.UPDATE_FIELDS, c.BC_PRIORITY, c.COPY ,c.END_DATE,c.ACCESS_PLATFORM_TYPE,pc.is_delete,pc.ONTRIAL,c.MP_ID,c.IS_MULTILIN_GUAL   ");
        sqlQuery.append("   from PRD_CONT pc, CONTENT c                                                                                                                    ");
        sqlQuery.append("  where pc.CONTENT_ID = C.CONTENT_ID                                                                                                              ");

        if (StringUtil.isNullStr(map.get("shieldDelCont"))
                || map.get("shieldDelCont").equals("1")) {
            sqlQuery.append(" and pc.IS_DELETE = 0  ");
        }

        if (!StringUtil.isNullStr(map.get("assist"))) {
            sqlQuery.append(" and c.assist like ? ");
            params.add("%" + StringUtil.null2Str(map.get("assist")) + "%");
        }
        if (!StringUtil.isNullStr(map.get("contentName"))) {
            sqlQuery.append(" and c.NAME like ? ");
            params.add("%" + StringUtil.null2Str(map.get("contentName")) + "%");
        }
        if (!StringUtil.isNullStr(map.get("accessPlatFormType"))) {
            sqlQuery.append(" and c.ACCESS_PLATFORM_TYPE = ?");
            params.add(StringUtil.nullToString(map.get("accessPlatFormType")));
        }

        if (!StringUtil.isNullStr(map.get("shieldDelCont"))
                && map.get("shieldDelCont").equals("1")) {
            sqlQuery.append(" and c.status in (0, 1, 3) ");
        }

        if (!StringUtil.isNullStr(map.get("bcType"))) {
            sqlQuery.append("  order by c.status desc, c.last_modify_time desc");
        } else {// 1-显示子集， 其他-不显示子集
            if (!"1".equals(StringUtil.nullToString(map.get("displaySubSet")))) {
                sqlQuery.append(" and c.FORM_TYPE != 7 ");
            }
        }


        if (!StringUtil.isNullStr(map.get("mpid"))) {
            sqlQuery.append(" and c.MP_ID = ?");
            params.add(StringUtil.nullToString(map.get("mpid")));
        }
        if (!StringUtil.isNullStr(map.get("MiguDBID"))) {
            sqlQuery.append(" and c.MIGU_DBID = ?");
            params.add(StringUtil.nullToString(map.get("MiguDBID")));
        }
        if (!StringUtil.isNullStr(map.get("mvid"))) {
            sqlQuery.append(" and c.MV_ID = ?");
            params.add(StringUtil.nullToString(map.get("mvid")));
        }
        if (!StringUtil.isNullStr(map.get("mcid"))) {
            sqlQuery.append(" and c.MC_ID = ?");
            params.add(StringUtil.nullToString(map.get("mcid")));
        }
        if (!StringUtil.isNullStr(map.get("author"))) {
            sqlQuery.append(" and c.author = ?");
            params.add(StringUtil.nullToString(map.get("author")));
        }

        if (!StringUtil.isNullStr(map.get("startTime"))) {
            sqlQuery.append(" and c.last_modify_time >= ? ");
            params.add(map.get("startTime"));
        }

        // 按一级分类，推荐标签，版权信息区分播控
        if (!StringUtil.isNullStr(map.get("firstClassifys"))) {
            String[] firstClassifys = StringUtil.null2Str(
                    map.get("firstClassifys")).split(",");
            sqlQuery.append(" and(");
            for (int i = 0; i < firstClassifys.length; i++) {
                if (i != 0) {
                    sqlQuery.append(" or ");
                }
                sqlQuery.append("c.DISPLAY_TYPE = ?");
                params.add(StringUtil.nullToString(firstClassifys[i]));
            }
            sqlQuery.append(")");
        }

        if (!StringUtil.isNullStr(map.get("copyRightCpIds"))) {
            String[] copyRightCpIds = StringUtil.null2Str(
                    map.get("copyRightCpIds")).split(",");
            sqlQuery.append(" and(");
            for (int i = 0; i < copyRightCpIds.length; i++) {
                if (i != 0) {
                    sqlQuery.append(" or ");
                }
                sqlQuery.append("c.copyright_cpid = ?");
                params.add(StringUtil.nullToString(copyRightCpIds[i]));
            }
            sqlQuery.append(")");
        }

        if (!StringUtil.isNullStr(map.get("recommendations"))) {
            String[] recommendations = StringUtil.null2Str(
                    map.get("recommendations")).split(",");
            sqlQuery.append(" and(");
            for (int i = 0; i < recommendations.length; i++) {
                if (i != 0) {
                    sqlQuery.append(" or ");
                }
                sqlQuery.append("c.RECOMMENDATION like ?");
                params.add(StringUtil.nullToString(recommendations[i]));
            }
            sqlQuery.append(")");
        }
        // 按一级分类，推荐标签，版权信息区分播控 end

        if (!StringUtil.isNullStr(map.get("endTime"))) {
            sqlQuery.append(" and c.last_modify_time <= ? ");
            params.add(map.get("endTime"));
        } else {
            sqlQuery.append(" and c.last_modify_time > to_char(sysdate-3,'yyyy-MM-dd')||' 00:00:00' ");
        }

        /*
         * sqlQuery.append(" and pc.PRD_INFO_ID = ? "); params.add(prdInfoId);
         */

        if (!StringUtil.isNullStr(map.get("selectType"))) {
            if ("1".equals(StringUtil.null2Str(map.get("selectType")))) {
                if (!StringUtil.isNullStr(map.get("selectProInfoId"))) {
                    sqlQuery.append(" and pc.PRD_INFO_ID = ?");
                    params.add(StringUtil.nullToLong(map.get("selectProInfoId")));
                } else {
                    sqlQuery.append(" and pc.PRD_INFO_ID in (select prdInfoId from PRD_INFO where PRODUCT_INFO_PACKAGE_ID = ? and is_Publish = 2)");
                    params.add(StringUtil.nullToLong(map.get("packageId")));
                }
            } else {
                sqlQuery.append(" and pc.PRD_INFO_ID = ?");
                params.add(prdInfoId);
            }
        } else {
            sqlQuery.append(" and pc.PRD_INFO_ID = ?");
            params.add(prdInfoId);
        }

        // 新增产品ID和权益节点ID查询
        if (!StringUtil.isNullStr(map.get("equityId"))) {
			/*sqlQuery.append(" and pc.EQUITY_ID = ?");
			params.add(StringUtil.nullToString(map.get("equityId")));*/
            sqlQuery.append(" and pc.EQUITY_ID like ?");
            params.add("%" + StringUtil.nullToString(map.get("equityId")) + "%");
        }
        if (!StringUtil.isNullStr(map.get("productId"))) {
            sqlQuery.append(" and pc.PRODUCT_ID = ?");
            params.add(StringUtil.nullToString(map.get("productId")));
        }

        List<Object[]> tmpList = new ArrayList<Object[]>();
        if (start == 0 && limit == 0) {
            tmpList = this.querySql(sqlQuery.toString(), params.toArray());
        } else {

            log.info("====已选内容池列表getListByLike通过名称查询: [" + sqlQuery + "]======================");
            if ("1".equals(StringUtil.null2Str(map.get("isExport")))) {
                tmpList = this.exportQuerySql(sqlQuery.toString(),
                        params.toArray(), start, limit);
            } else {
                tmpList = this.querySql(sqlQuery.toString(), params.toArray(),
                        start, limit);
            }
        }

        List<ContentVo> contentVoList = new ArrayList<ContentVo>();
        for (Object[] obj : tmpList) {
            ContentVo vo = new ContentVo();
            if (obj[0] != null) {
                vo.setPrdContId(StringUtil.nullToLong(obj[0]));
            }
            if (obj[1] != null) {
                vo.setContentId(StringUtil.nullToLong(obj[1]));
            }
            vo.setName(StringUtil.nullToString(obj[2]));
            if (obj[3] != null) {
                vo.setCduration(StringUtil.nullToLong(obj[3]));
            }
            if (obj[4] != null) {
                vo.setCpId(StringUtil.nullToLong(obj[4]));
            }
            vo.setKeyWords(StringUtil.nullToString(obj[5]));
            if (obj[6] != null) {
                vo.setFirstClassify(StringUtil.nullToLong(obj[6]));
            }
            if (obj[7] != null) {
                vo.setScopeAuthor(StringUtil.nullToInteger(obj[7]));
            }
            if (obj[8] != null) {
                vo.setCopyRightType(StringUtil.nullToInteger(obj[8]));
            }
            if (obj[9] != null) {
                vo.setFreeType(StringUtil.nullToInteger(obj[9]));
            }
            if (obj[10] != null) {
                vo.setBcStatus(StringUtil.nullToInteger(obj[10]));
            }
            if (obj[11] != null) {
                vo.setDistStatus(StringUtil.nullToInteger(obj[11]));
            }
            if (obj[12] != null) {
                vo.setPubStatus(StringUtil.nullToInteger(obj[12]));
            }
            if (!StringUtil.isNullStr(obj[13])) {
                vo.setCreateTime(StringUtil.nullToString(obj[13]));
            } else {
                vo.setCreateTime("");
            }
            if (obj[14] != null) {
                vo.setId(StringUtil.nullToLong(obj[14]));
            }
            vo.setStatus(StringUtil.nullToString(obj[15]));
            vo.setCategory(StringUtil.nullToString(obj[16]));
            if (obj[17] != null) {
                vo.setAssetId(StringUtil.nullToLong(obj[17]));
            }
            vo.setBcrefuseReason(StringUtil.nullToString(obj[18]));
            vo.setFormType(StringUtil.nullToString(obj[19]));
            vo.setIsEmergency(StringUtil.nullToString(obj[20]));
            if (obj[22] != null) {
                vo.setGslbStatus(StringUtil.nullToString(obj[22]));
            }
            if (obj[21] != null) {
                vo.setCdnStatus(StringUtil.nullToString(obj[21]));
            }
            if (obj[23] != null) {
                vo.setType(StringUtil.nullToString(obj[23]));
            }
            if (obj[24] != null) {
                vo.setPublishNoVOMSStatus(StringUtil.nullToString(obj[24]));
            }
            if (obj[25] != null) {
                vo.setMovieLibId(StringUtil.nullToString(obj[25]));
            }
            if (obj[26] != null) {
                vo.setPrdInfoId(StringUtil.nullToLong(obj[26]));
            }
            if (obj[27] != null) {
                vo.setSalConfigPrice(StringUtil.nullToString(obj[27]));
            }
            if (obj[28] != null) {
                vo.setSalPromPrice(StringUtil.nullToString(obj[28]));
            }
            if (obj[29] != null) {
                vo.setDetail(StringUtil.nullToString(obj[29]));
            }
            if (obj[30] != null) {
                vo.setCacheCdnStatus(StringUtil.nullToString(obj[30]));
            }
            if (obj[31] != null) {
                vo.setUpdateFields(StringUtil.null2Str(obj[31]).replaceAll("，",
                        ","));
            }
            if (obj[32] != null) {
                vo.setBcPriority(StringUtil.null2Str(obj[32]));
            }

            if (obj[33] != null) {
                vo.setCopy(StringUtil.null2Str(obj[33]));
            }
            if (obj[34] != null) {
                vo.setEndDate(StringUtil.null2Str(obj[34]));
            }
            if (obj[35] != null) {
                vo.setAccessPlatFormType(StringUtil.null2Str(obj[35]));
            }
            if (obj[36] != null) {
                vo.setIsDelete(StringUtil.nullToInteger(obj[36]));
            }
            if (obj[37] != null) {
                vo.setOnTrial(StringUtil.nullToInteger(obj[37]));
            } else {
                vo.setOnTrial(1);
            }
            if (obj[38] != null) {
                vo.setMpid(StringUtil.null2Str(obj[38]));
            }
            if (obj[38] != null) {
                vo.setIsMultilingual(StringUtil.null2Str(obj[39]));
            }

            contentVoList.add(vo);
        }
        return contentVoList;
    }

    @Override
    public Page<PrdContVo> findAll(PrdContSelPojo prdContSelPojo, int page, int rows, String sord, String sidx) {
        StringBuilder condition = sqlStringWhere(true, prdContSelPojo, sord, sidx);
        Object o = entityManager
                .createNativeQuery(condition.toString()).getSingleResult();
        int count = Convert.toInt(o);
        Pageable pageable = PageRequest.of(page - 1, rows);
        if (count > 0) {
            condition = sqlStringWhere(false, prdContSelPojo, sord, sidx);
            Query query = entityManager.createNativeQuery(condition.toString());
            query.setFirstResult(pageable.getPageNumber() * pageable.getPageSize());
            query.setMaxResults(pageable.getPageSize());
            List<Object[]> list = query.getResultList();
            List<PrdContVo> prdContVoList = toPrdContVoList(list);
            ;
            PageImpl<PrdContVo> result = new PageImpl<PrdContVo>(prdContVoList, pageable, count);
            entityManager.close();
            return result;
        }
        entityManager.close();
        return Page.empty(pageable);
    }

    @Override
    public List<PrdContVo> findPrdContVoList(PrdContSelPojo prdContSelPojo, int page, int rows, String sord, String sidx) {
        StringBuilder condition = sqlStringWhere(false, prdContSelPojo, sord, sidx);
        Query query = entityManager.createNativeQuery(condition.toString());
        List<Object[]> list = query.getResultList();
        return toPrdContVoList(list);
    }

    @Override
    public PrdContDetailVo findPrdContDetailVoById(Long prdContId) {
        PrdCont prdCont = prdContDao.findByPrdContId(prdContId);
        PrdContMinVo prdContMinVo = new PrdContMinVo();
        if (prdCont != null) {
            prdContMinVo.setPubStatus(prdCont.getPubStatus());
            prdContMinVo.setPrdContId(prdCont.getPrdContId());
            prdContMinVo.setDistStatus(prdCont.getDistStatus());
            prdContMinVo.setContentId(prdCont.getContentId());
            prdContMinVo.setBcStatus(prdCont.getBcStatus());
            prdContMinVo.setBcRefuseReason(prdCont.getBcRefuseReason());
        }
        Content content = null;
        if (StringUtils.isNotBlank(prdCont.getContentId())) {
            content = contentDao.findByContentId(prdCont.getContentId());
        }
        return new PrdContDetailVo(prdContMinVo, content, null);
    }

    @Override
    public ResultBean findPrdContDetailImgById(Long prdContId, Long contentId) throws IOException {
        String content = StringUtil.nullToString(contentId);
        if (prdContId == null && contentId == null) {
            return ResultBean.error("内容或节目id至少传一个");
        }
        if (contentId == null) {
            PrdCont prdCont = prdContDao.findByPrdContId(prdContId);
            if (prdCont != null) {
                content = prdCont.getContentId();
                if (StringUtils.isBlank(content)) {
                    return ResultBean.error("节目id没有对应内容");
                }
            } else {
                return ResultBean.error("节目id没有对应内容");
            }
        }
        return ResultBean.ok(imageService.getImagesWithoutWebp(content));
    }


    @Override
    public List<LivePlayVo> findLivePlayList(String prdInfoId, String contentId, String dateTime, String endTime) {
        StringBuilder sbf = new StringBuilder();
        if (!StringUtils.isEmpty(prdInfoId)) {
            ProductInfoPackage productInfoPackage = productInfoPackageDao.getValidProductInfoPackage(Long.parseLong(prdInfoId));
            if (productInfoPackage != null && productInfoPackage.getProductInfoPackageId() != null) {
                List<PrdInfo> list = prdInfoDao.findPrdInfoInPackageId
                        (productInfoPackage.getProductInfoPackageId(), 2);
                if (list.size() > 0) {
                    for (PrdInfo prdInfo : list) {
                        sbf.append(prdInfo.getPrdInfoId() + ",");
                    }
                }
            } else {
                sbf.append(prdInfoId);
            }
        }

        StringBuffer sql = new StringBuffer();
        sql.append("   SELECT pc.PRD_CONT_ID,                                               " +
                "        c.content_id,                                                      " +
                "        c.asset_id,                                                        " +
                "        c.name,                                                            " +
                "        c.LIVE_CONTENT_ID,c.PLAY_BILL_START_TIME,c.PLAY_BILL_END_TIME,c.status," +
                "        pc.bc_status,pc.publish_no_voms_status,     						" +
                "        c.serial_sequence,                                                 " +
                "        c.serial_trailing_sequence     									" +
                "   FROM content c                                                          " +
                "   LEFT JOIN (SELECT *                                                     " +
                "                FROM prd_cont                                              " +
                "               WHERE is_delete = 0 AND file_action <> 2   ");
        if (!StringUtils.isEmpty(prdInfoId) && !StringUtils.isEmpty(sbf.toString())) {
            String prdInfoIdS = sbf.toString();
            prdInfoIdS = prdInfoIdS.substring(0, prdInfoIdS.length() - 1);
            sql.append(" AND prd_info_id in (").append(prdInfoIdS).append(")");
        }
        sql.append(") pc on c.content_id = pc.content_id ");
        sql.append("  WHERE c.status != 2 ");
        if (!StringUtils.isEmpty(contentId)) {
            sql.append("  AND c.LIVE_CONTENT_ID = ").append(contentId);
        }
        if (!StringUtils.isEmpty(dateTime)) {
            sql.append(" and TO_DATE(c.PLAY_BILL_START_TIME,'yyyy-MM-dd HH24:mi:ss') >=  TO_DATE('" + dateTime + "', 'yyyy-MM-dd HH24:mi:ss')");

        }
        if (!StringUtils.isEmpty(endTime)) {
            sql.append(" and TO_DATE(c.PLAY_BILL_START_TIME,'yyyy-MM-dd HH24:mi:ss') < TO_DATE('" + endTime + "', 'yyyy-MM-dd HH24:mi:ss')");

        }
        sql.append("  ORDER BY c.PLAY_BILL_START_TIME ASC,to_number(c.serial_sequence) ASC, to_number(c.serial_trailing_sequence) ASC ");
        log.info("PrdContServiceImpl#findLivePlayList_sql:" + sql);
        Query query = entityManager.createNativeQuery(sql.toString());
        List<Object[]> resultList = query.getResultList();
        return listToLivePlayVoList(resultList);
    }

    List<LivePlayVo> listToLivePlayVoList(List<Object[]> resultList) {
        List<LivePlayVo> list = new LinkedList<>();
        for (Object[] obj : resultList) {
            LivePlayVo lp = new LivePlayVo();
            lp.setPlayBillId(StringUtil.null2Str(obj[0]));
            lp.setContentId(StringUtil.null2Str(obj[1]));
            lp.setAssetId(StringUtil.null2Str(obj[2]));
            lp.setName(StringUtil.null2Str(obj[3]));
            lp.setChannelId(StringUtil.null2Str(obj[4]));
            lp.setPlaybillStartTime(StringUtil.null2Str(obj[5]));
            lp.setPlaybillEndTime(StringUtil.null2Str(obj[6]));
            lp.setAssetStatus(StringUtil.null2Str(obj[7]));
            lp.setCreateTime(StringUtil.null2Str(obj[8]));
            lp.setBcStatus(StringUtil.null2Str(obj[9]));
            lp.setPublishStatus(StringUtil.null2Str(obj[10]));
            list.add(lp);
        }
        return list;
    }

    @Override
    public ResultBean findLivePlaybillList(String prdContId, String contentId, String playDay) {
        if (StringUtils.isBlank(prdContId)) {
            return ResultBean.error("节目id不能为空");
        }
        if (StringUtils.isBlank(contentId)) {
            return ResultBean.error("内容id不能为空");
        }
        if (StringUtils.isBlank(playDay)) {
            return ResultBean.error("播放日期不能为空");
        }
        StringBuffer sqlQuery = new StringBuffer("SELECT pb.ID, pb.START_TIME, pb.END_TIME, pb.PROGRAM, pb.RANKING, pb.SEQ_RANK, pb.PLAY_SHELL_ID, pb.PLAY_VOD_ID  FROM PLAY_BILL pb 'joinCondition' WHERE 1=1 ");
        if (!StringUtil.isNullStr(prdContId)) {
            String tempStr = String.format(sqlQuery.toString(), ", dr.DIRECT_REC_FLAG ");
            sqlQuery = new StringBuffer(tempStr.replaceAll("'joinCondition'", " LEFT OUTER JOIN DIRECT_REC_LIVE dr on (pb.SEQ_RANK = dr.CONTENT_SEQUENCE AND dr.PRD_CONT_ID = " + prdContId + " ) "));
        } else {
            sqlQuery = new StringBuffer(String.format(sqlQuery.toString(), " ").replaceAll("'joinCondition'", ""));
        }

        if (!StringUtil.isNullStr(contentId)) {
            sqlQuery.append(" AND pb.CONTENT_ID = " + contentId);
        }

        if (!StringUtil.isNullStr(playDay)) {
            sqlQuery.append(" AND pb.PLAY_DAY = '" + playDay + "'");
        }
        sqlQuery.append(" ORDER BY to_number(pb.RANKING) ASC,  to_date(pb.START_TIME, 'yyyyMMddHH24miss') ASC ");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        List<LivePlaybillVo> billLists = new ArrayList<LivePlaybillVo>();
        Query query = entityManager.createNativeQuery(sqlQuery.toString());
        List<Object[]> tmpList = query.getResultList();
        if (tmpList != null && tmpList.size() > 0) {
            for (Object[] obj : tmpList) {
                LivePlaybillVo bill = new LivePlaybillVo();
                bill.setBillId(StringUtil.null2Str(obj[0]));
                Date startTime = StringUtil.nullToDate(obj[1], "yyyyMMddHHmmss");
                Date endTime = StringUtil.nullToDate(obj[2], "yyyyMMddHHmmss");
                bill.setStartTime(sdf.format(startTime));
                bill.setEndTime(sdf.format(endTime));
                String playName = StringUtil.null2Str(obj[3]).replaceAll("'", "");
                bill.setPlayName(playName);
                bill.setRanking(StringUtil.null2Str(obj[4]));
                bill.setSequence(StringUtil.null2Str(obj[5]));
                bill.setPlayShellID(StringUtil.null2Str(obj[6]));
                bill.setPlayVodID(StringUtil.null2Str(obj[7]));
                if (!StringUtils.isEmpty(prdContId)) {
                    bill.setDirectRecFlag(StringUtil.null2Str(obj[8]));
                }
                billLists.add(bill);
            }
        }
        entityManager.close();
        return ResultBean.ok(billLists);
    }

    @Override
    public List<TreeVo> findPrdAndCont() {
        String ids = systemConfigService.findAllBykey("FIRSTPRODUCT_BESIDES_IDS") == null ? "" : systemConfigService.findAllBykey("FIRSTPRODUCT_BESIDES_IDS").getValue();
        StringBuilder sql = new StringBuilder();
        sql.append("select concat('fir-',fp.FIRST_PRODUCT_ID),fp.FIRST_PRODUCT_NAME,concat('two-',pp.PRODUCT_INFO_PACKAGE_ID),pp.PRODUCT_INFO_PACKAGE_NAME, " +
                "concat('thr-',pi.PRDINFOID),pi.NAME " +
                "from first_product_info_package fp,product_info_package pp " +
                "left join PRD_INFO pi on (pp.PRODUCT_INFO_PACKAGE_ID=pi.PRODUCT_INFO_PACKAGE_ID and pi.IS_PUBLISH=2 and (pi.SYSTEM_FLAG = 2 or pi.SYSTEM_FLAG is NULL) )      " +
                "where fp.FIRST_PRODUCT_ID=pp.FIRST_PRODUCT_INFO_PACKAGE_ID  " +
                "and fp.STATUS=1 and (pp.SYSTEM_FLAG = 2 or pp.SYSTEM_FLAG is NULL)  ");
        if (StringUtils.isNotBlank(ids)) {
            sql.append("fp.FIRST_PRODUCT_ID not in(" + ids + ")");
        }
        sql.append("order by pp.PRODUCT_INFO_PACKAGE_ID,pi.PRDINFOID");
        Query query = entityManager.createNativeQuery(sql.toString());
        List<Object[]> list = query.getResultList();
        //层级2
        List<TreeVo> list2 = new ArrayList<>();
        //层级1
        List<TreeVo> list1 = new ArrayList<>();
        //23:放对应产品(商品包)包到二级产品层级  数据少  逻辑简单化
        for (int k = 0; k < list.size(); k++) {
            TreeVo tree = new TreeVo(StringUtil.nullToString(list.get(k)[2]),
                    StringUtil.nullToString(list.get(k)[3]), StringUtil.nullToString(list.get(k)[0]), StringUtil.nullToString(list.get(k)[1]), 2, 0, new ArrayList<TreeVo>());
            if (list2.size() == 0) {
                if (list.get(k)[5] != null) {
                    TreeVo childrenTree = new TreeVo(StringUtil.nullToString(list.get(k)[4]),
                            StringUtil.nullToString(list.get(k)[5]), StringUtil.nullToString(list.get(k)[2]), StringUtil.nullToString(list.get(k)[3]), 3, 0, null);
                    tree.addChildrenTree(childrenTree);
                }
                list2.add(tree);
            } else if (!StringUtil.nullToString(list.get(k)[2]).equals(list2.get(list2.size() - 1).getId())) {
                if (list.get(k)[5] != null) {
                    TreeVo childrenTree = new TreeVo(StringUtil.nullToString(list.get(k)[4]),
                            StringUtil.nullToString(list.get(k)[5]), StringUtil.nullToString(list.get(k)[2]), StringUtil.nullToString(list.get(k)[3]), 3, 0, null);
                    tree.addChildrenTree(childrenTree);
                }
                list2.add(tree);
            } else {
                if (list.get(k)[5] != null) {
                    tree = list2.get(list2.size() - 1);
                    TreeVo childrenTree = new TreeVo(StringUtil.nullToString(list.get(k)[4]),
                            StringUtil.nullToString(list.get(k)[5]), StringUtil.nullToString(list.get(k)[2]), StringUtil.nullToString(list.get(k)[3]), 3, 0, null);
                    tree.addChildrenTree(childrenTree);
                    list2.set(list2.size() - 1, tree);
                }
            }
        }
        list2.sort(new Comparator<TreeVo>() {
            @Override
            public int compare(TreeVo o1, TreeVo o2) {
                //升序
                return o1.getParentId().compareTo(o2.getParentId());
            }
        });

        //12:放对应二级产品到一级产品层级
        for (int k = 0; k < list2.size(); k++) {
            TreeVo tree2 = list2.get(k);
            if (list1.size() == 0) {
                TreeVo tree1 = new TreeVo(tree2.getParentId(), tree2.getParentName(), "0", "", 1, 0, new ArrayList<TreeVo>());
                tree1.addChildrenTree(tree2);
                list1.add(tree1);
            } else if (list1.get(list1.size() - 1).getId().equals(tree2.getParentId())) {
                TreeVo tree1 = list1.get(list1.size() - 1);
                tree1.addChildrenTree(tree2);
                list1.set(list1.size() - 1, tree1);
            } else {
                TreeVo tree1 = new TreeVo(tree2.getParentId(), tree2.getParentName(), "0", "", 1, 0, new ArrayList<TreeVo>());
                tree1.addChildrenTree(tree2);
                list1.add(tree1);
            }
        }
        return findFirstPrdAndCont(ids, list1);
    }

    @Override
    public List<TreeVo> findFirstPrdAndCont(String ids) {
        StringBuilder sql = new StringBuilder();
        sql.append("select concat('fir-',fp.FIRST_PRODUCT_ID),fp.FIRST_PRODUCT_NAME,concat('thr-',pi.PRDINFOID),pi.NAME " +
                "from first_product_info_package fp,PRD_INFO pi " +
                "where pi.FIRST_PRODUCT_INFO_PACKAGE_ID=fp.FIRST_PRODUCT_ID and pi.PRODUCT_INFO_PACKAGE_ID  is null " +
                "and  pi.PRDINFOID is not null fp.STATUS=1  and pi.IS_PUBLISH=2 and (pi.SYSTEM_FLAG = 2 or pi.SYSTEM_FLAG is NULL)  ");
        if (StringUtils.isNotBlank(ids)) {
            sql.append("fp.FIRST_PRODUCT_ID not in(" + ids + ")");
        }
        sql.append(" order by fp.FIRST_PRODUCT_ID,pi.PRDINFOID");
        Query query = entityManager.createNativeQuery(sql.toString());
        List<Object[]> list = query.getResultList();
        //层级1
        List<TreeVo> list1 = new ArrayList<>();
        //13:放产品(商品)包到一级产品层级
        for (int k = list.size() - 1; k > -1; k--) {
            TreeVo tree = new TreeVo(StringUtil.nullToString(list.get(k)[0]),
                    StringUtil.nullToString(list.get(k)[1]), "0", "", 1, 0, new ArrayList<TreeVo>());
            if (list1.size() == 0) {
                list1.add(tree);
            } else if (!StringUtil.nullToString(list.get(k)[2]).equals(list1.get(list1.size() - 1).getId())) {
                list1.add(tree);
            }
        }
        int index1 = list1.size() - 1;
        for (int k = list.size() - 1; k > -1; k--) {
            TreeVo childrenTree = new TreeVo(StringUtil.nullToString(list.get(k)[2]),
                    StringUtil.nullToString(list.get(k)[3]), StringUtil.nullToString(list.get(k)[0]), StringUtil.nullToString(list.get(k)[1]), 3, 0, null);
            if (StringUtil.nullToString(list.get(k)[0]).equals(list1.get(index1).getId())) {
                TreeVo tree = list1.get(index1);
                tree.addChildrenTree(childrenTree);
                list1.set(index1, tree);
            } else {
                index1--;
            }
        }
        return list1;
    }

    public List<TreeVo> findFirstPrdAndCont(String ids, List<TreeVo> listForm) {
        StringBuilder sql = new StringBuilder();
        sql.append("select concat('fir-',fp.FIRST_PRODUCT_ID),fp.FIRST_PRODUCT_NAME,concat('thr-',pi.PRDINFOID),pi.NAME " +
                "from first_product_info_package fp,PRD_INFO pi " +
                "where pi.FIRST_PRODUCT_INFO_PACKAGE_ID=fp.FIRST_PRODUCT_ID and pi.PRODUCT_INFO_PACKAGE_ID  is null " +
                "and  pi.PRDINFOID is not null and fp.STATUS=1  and pi.IS_PUBLISH=2 and (pi.SYSTEM_FLAG = 2 or pi.SYSTEM_FLAG is NULL)  ");
        if (StringUtils.isNotBlank(ids)) {
            sql.append("fp.FIRST_PRODUCT_ID not in(" + ids + ")");
        }
        sql.append(" order by fp.FIRST_PRODUCT_ID,pi.PRDINFOID");
        Query query = entityManager.createNativeQuery(sql.toString());
        List<Object[]> list = query.getResultList();
        if (list == null || list.size() == 0) {
            return listForm;
        }
        //层级1
        List<TreeVo> list1 = new ArrayList<>();
        //13:放产品(商品)包到一级产品层级
        for (int k = list.size() - 1; k > -1; k--) {
            TreeVo tree = new TreeVo(StringUtil.nullToString(list.get(k)[0]),
                    StringUtil.nullToString(list.get(k)[1]), "0", "", 1, 0, new ArrayList<TreeVo>());
            if (list1.size() == 0) {
                list1.add(tree);
            } else if (!StringUtil.nullToString(list.get(k)[2]).equals(list1.get(list1.size() - 1).getId())) {
                list1.add(tree);
            }
        }
        int index1 = list1.size() - 1;
        for (int k = list.size() - 1; k > -1; k--) {
            TreeVo childrenTree = new TreeVo(StringUtil.nullToString(list.get(k)[2]),
                    StringUtil.nullToString(list.get(k)[3]), StringUtil.nullToString(list.get(k)[0]), StringUtil.nullToString(list.get(k)[1]), 3, 0, null);
            if (StringUtil.nullToString(list.get(k)[0]).equals(list1.get(index1).getId())) {
                TreeVo tree = list1.get(index1);
                tree.addChildrenTree(childrenTree);
                list1.set(index1, tree);
            } else {
                for (int j = listForm.size() - 1; j > -1; j--) {
                    TreeVo tree = list1.get(index1);
                    TreeVo treeForm = listForm.get(j);
                    if (treeForm.getId().equals(treeForm.getId())) {
                        treeForm.addChildrenList(tree.getChildren());
                        listForm.set(j, treeForm);
                        list1.remove(index1);
                    }
                }
                index1--;
            }
        }
        if (list1 != null && list1.size() > 0) {
            listForm.addAll(list1);
        }
        return listForm;
    }

    @Override
    @Transactional
    public int batchUpdateIsEmergencyById(String isEmergency, List<Long> prdContIds) {
        return prdContDao.batchUpdateIsEmergencyById(isEmergency, prdContIds);
    }

    @Override
    public ResultBean emergencyBc(String prdContIds, String contentIds, String level) {
        ResultBean resultBean = new ResultBean();
        log.info("PrdContServiceImpl#emergencyBc_剧集壳" + prdContIds);
        if (StringUtil.isNullStr(contentIds)) {
            return ResultBean.error("内容id不能为空");
        }
        if (!StringUtil.isNullStr(prdContIds)) {
            String[] arrayPrdContIds = prdContIds.split(",");
            for (String prdContId : arrayPrdContIds) {
                PrdCont prdCont = prdContDao.findByPrdContId(Long.parseLong(prdContId));
                if (prdCont != null) {
                    List<SerialVo> serialList = getSerialList(prdCont.getContentId(), prdCont.getPrdInfoId().toString(), null);
                    for (SerialVo vo : serialList) {
                        if ("0".equals(vo.getBcStatus())
                                && !"2".equals(vo.getStatus())) {
                            contentIds = contentIds + "," + vo.getContentId();
                        }
                    }
                }
            }
        }
        String[] allContIds = contentIds.split(",");
        Boolean falg = false;
        if (allContIds.length == 1) {
            falg = true;
        }
        log.info("contentIds:" + contentIds + ";level:" + level
                + "============");
        String[] arrayContentIds = contentIds.split(",");
        String url = StringUtil.null2Str(systemConfigService.findAllBykey("EMERGENCYBC_BC_URL").getValue());
        NameValuePair[] values = {
                new NameValuePair("prdContInfoId", contentIds),
                new NameValuePair("priority", level)};
        String str = "";
        try {
            str = HttpClientUtil.requestGet(url, values);
        } catch (Exception e) {
            resultBean.setCode(GlobalCodeEnum.FAILURE.getCode());
            resultBean.setMsg(msgConfig.getEmergencyBcSystemBusy());
            return resultBean;
        }
        if (StringUtil.isNullStr(str)) {
            resultBean.setCode(GlobalCodeEnum.FAILURE.getCode());
            resultBean.setMsg(msgConfig.getEmergencyBcSystemBusy());
            return resultBean;
        }
        JSONObject json = JSONObject.parseObject(str);
        String code = json.getString("code");
        log.info("code" + code + "========");
        if ("9999".equals(code)) {
            resultBean.setCode(GlobalCodeEnum.FAILURE.getCode());
            resultBean.setMsg(msgConfig.getEmergencyBcSystemError());
        } else if ("0000".equals(code)) {
            for (String contId : allContIds) {
                Content content = contentDao.findByContentId(contId);
                EmergencyBcLog emergencyBcLog = new EmergencyBcLog(contId,
                        content.getName(), level, "1", "");
                emergencyBcLogDao.save(emergencyBcLog);
            }
            resultBean.setCode(GlobalCodeEnum.SUCCESS.getCode());
            resultBean.setMsg("成功");
        } else if ("0004".equals(code)) {
            String message = json.getString("message");
            log.info("message" + message + "========");
            for (String contId : allContIds) {
                Content content = contentDao.findByContentId(contId);
                if (message.contains(contId)) {// 失败的
                    EmergencyBcLog emergencyBcLog = new EmergencyBcLog(contId,
                            content.getName(), level, "2", msgConfig.getEmergencyBcContentError());
                    emergencyBcLogDao.save(emergencyBcLog);
                } else {
                    EmergencyBcLog emergencyBcLog = new EmergencyBcLog(contId,
                            content.getName(), level, "1", "");
                    emergencyBcLogDao.save(emergencyBcLog);
                }
            }
            if (falg) {
                resultBean.setCode(GlobalCodeEnum.FAILURE.getCode());
                resultBean.setMsg(msgConfig.getEmergencyBcContentError());
            } else {
                resultBean.setCode(GlobalCodeEnum.SUCCESS.getCode());
                resultBean.setMsg(message + ":" + msgConfig.getEmergencyBcContentError());
            }
        } else if ("0001".equals(code)) {
            for (String contId : allContIds) {
                Content content = contentDao.findByContentId(contId);
                EmergencyBcLog emergencyBcLog = new EmergencyBcLog(contId,
                        content.getName(), level, "2", msgConfig.getEmergencyBcContentError());
                emergencyBcLogDao.save(emergencyBcLog);
            }
            resultBean.setCode(GlobalCodeEnum.FAILURE.getCode());
            resultBean.setMsg(msgConfig.getEmergencyBcContentError());
        } else if ("0002".equals(code) || "0003".equals(code)) {
            resultBean.setCode(GlobalCodeEnum.FAILURE.getCode());
            resultBean.setMsg(msgConfig.getEmergencyBcPramError());
        }
        return ResultBean.ok();
    }

    @Override
    public List<ImageVo> getPubImages(String contentId) {
        contentId = decrypt(contentId);
        log.info("===============AES解密后的contentId为：" + contentId + "===============");
        String ip = systemConfigService.findAllBykey("PROVINCE_PREVIEW_IP").getValue();
        List<ImageVo> imagesList = new ArrayList<ImageVo>();
        if (StringUtils.isNotBlank(contentId)) {
        }
        String imgPath = null;
        String baseImgPath = systemConfigService.findAllBykey("PUBLISH_IMAGE_BASE_PATH").getValue();
        if (baseImgPath != null && baseImgPath.length() > 1) {
            imgPath = baseImgPath.split(",")[0] + "/" + contentId.substring(0, 4) + "/" + contentId.substring(4, 7)
                    + "/" + contentId.substring(7) + "/";
        }
        log.info("PrdContServiceImpl#getPubImages_imgPath" + imgPath);
        if (imgPath != null) {
            File f = new File(imgPath);
            if (f.exists() && f.isDirectory()) {
                File[] fs = f.listFiles();
                for (int i = 0; i < fs.length; i++) {
                    File ff = fs[i];
                    if (ff.isFile()) {
                        ImageVo img = new ImageVo();
                        img.setName(ff.getName());
                        String[] src = ff.getAbsolutePath().split("cmvideo");
                        img.setSrc(ip + src[1]);
                        img.setImgSize((float) Math.round((ff.length() / 1024.0f) * 10) / 10);//图片大小,单位KB,保留一位小数
                        imagesList.add(img);
                    }
                }
            }
        }
        return imagesList;
    }

    @Override
    public PrdCont getPrdContByPrdContId(Long prdContId) {
        return prdContDao.findByPrdContId(prdContId);
    }

    @Override
    public PrdCont getShellPrdContByMsssIdAndPrdInfoId(Long mmisId, Long prdInfoId) {
        List<PrdCont> prdConts = prdContDao.getShellPrdContByMsssIdAndPrdInfoId(mmisId, prdInfoId);
        if (CollectionUtil.isNotEmpty(prdConts)) {
            return prdConts.get(0);
        }
        return null;
    }

    @Override
    public String findDetailByContentId(String contentid) {
        return contentDao.findDetailByContentId(contentid);
    }

    @Override
    public Integer findNewPubStatusByPrdContId(Long prdContId) {
        return prdContDao.findNewPubStatusByPrdContId(prdContId);
    }

    @Override
    public ResultBean addMiss(Long prdContId) {
        PrdCont prdCont = prdContDao.findByPrdContId(prdContId);
        String platFormTypes = systemConfigService.findAllBykey("NEED_DIST_PLATFORM_TYPE") == null
                ? "" : systemConfigService.findAllBykey("NEED_DIST_PLATFORM_TYPE").getValue();
        //89, 189
        String[] platTypes = platFormTypes.split(",");

        String contentId = prdCont.getContentId();
        Long prdInfoId = prdCont.getPrdInfoId();
        PrdInfo prodInfo = prdInfoDao.findByPrdInfoId(prdInfoId);

        List<SerialVo> prdContlList = getSerialList(contentId, prdInfoId.toString(), null);//节目
        String kafkaSwitch = systemConfigService.findAllBykey("KAFKA_SWITCH") == null
                ? "" : systemConfigService.findAllBykey("KAFKA_SWITCH").getValue();
        List<PrdCont> prdConts = new ArrayList<PrdCont>();
        boolean flag = false;
        for (SerialVo vo : prdContlList) {
            if (StringUtil.isNullStr(vo.getPrdContId())) {
                flag = true;
                Content content = contentDao.findByContentId(vo.getContentId());
                long sCount = prdContDao.getCountByContIdAndPrdInfoId(content.getContentId(), prdInfoId);
                if (sCount == 0) {
                    PrdContBo pcTemp = new PrdContBo(content, prodInfo);
                    //===需求变动，播控拒绝也要像播控通过一样复用， 2017-11-16 tangyingjun， begin====
                    if (prodInfo != null && prodInfo.getBcId() != null && 1 == prodInfo.getIsBc()) {
                        List<PrdCont> prdContList = prdContDao.findAllByContentIdAndIsDelete(content.getContentId(), 0);
                        if (prdContList != null && prdContList.size() > 0) {
                            for (PrdCont pc : prdContList) {
                                if (pc.getPrdInfoId() != null && StringUtil.null2Str(pc.getBcId()).equals(StringUtil.null2Str(prodInfo.getBcId()))) {
                                    if (pc.getBcStatus() != 0) {//0-待播控， 1-播控通过， 2-播控拒绝
                                        pcTemp.setBcId(pc.getBcId());
                                        pcTemp.setBcPerson(pc.getBcPerson());
                                        pcTemp.setBcTime(pc.getBcTime());
                                        pcTemp.setBcStatus(pc.getBcStatus());
                                        pcTemp.setBcRefuseReason(pc.getBcRefuseReason());
                                        break;
                                    }
                                }
                            }
                        }

                    }
                    //===需求变动，播控拒绝也要像播控通过一样复用， 2017-11-16 tangyingjun， end====
                    //MAM平台同步且已分发的内容直接节目置为已分发
                    for (String platType : platTypes) {//89, 189
                        if (platType.equals(content.getAccessPlatformType()) && "1".equals(content.getDistResult()) && !"2".equals(StringUtil.null2Str(content.getStatus()))) {
                            List<PrdCont> tempPcList = prdContDao.findAllByContentIdAndIsDelete(content.getContentId(), 0);
                            if (tempPcList != null && tempPcList.size() > 0) {
                                PrdCont tempPc = tempPcList.get(0);
                                pcTemp.setDistTime(tempPc.getDistTime());
                            } else {
                                pcTemp.setDistTime(new Date());
                            }
                            pcTemp.setDistStatus(12);
                        }
                    }

                    if ("1".equals(StringUtil.null2Str(content.getStatus())) || "3".equals(StringUtil.null2Str(content.getStatus()))) {
                        pcTemp.setCisStatus("2");
                    }

//					pcTemp = defaultPrdSalManager.chargePrdCont(pcTemp, content);
//					PrdCont dbJms = prdContManager.save(pcTemp);

//					/*-----------记录用户移动内容的日志--------------start--------------------*/
//					UserMoveLog operaterLog = new UserMoveLog();
//					operaterLog.setContentId(dbJms.getContentId());
//					operaterLog.setPrdContId(dbJms.getPrdContId());
//					operaterLog.setNewPrdInfoId(dbJms.getPrdInfo().getPrdInfoId());
//					operaterLog.setCreateTime(new Date());
//					operaterLog.setOperaterUser(this.getUsername());
//
//					String cNames = contentManager.getByContentId(dbJms.getContentId()).getName();
//					operaterLog.setContentName(cNames);
//					operaterLog.setFirstPrdInfoPackage(dbJms.getPrdInfo().getFirstProductInfoPackageId());
//					operaterLog.setSecondPrdInfoPackage(dbJms.getPrdInfo().getProductInfoPackageId());
//
//					this.userMoveLogManager.save(operaterLog);
//					/*--------------------------end----------------------*/
                    //推送kafka
                    try {
                        if ("on".equals(kafkaSwitch.trim().toLowerCase())) {
//							if("699004".equals(StringUtil.null2Str(dbJms.getBcId()))){
//								if(dbJms.getBcStatus() == PrdContBo.BC_STATUS_NOT ){
//									prdConts.add(dbJms);
//								}
//							}
                        }
                    } catch (Exception e) {
//						log.info("剧集壳:"+prdContId+"的子集"+dbJms.getPrdContId()+"推送失败");
                        e.printStackTrace();
                    }
                }
            }
        }
        //发送mq
//		publishThreadPool.execute(new sendPrdContsKafkaThread(prdConts));
        return null;
    }

    //解密算法
    private String decrypt(String hex) {
        // 解码16进制字符串
        if (StringUtil.isNullStr(hex)) {
            return null;
        }
        try {
            BigInteger bi = new BigInteger(hex, 16);
            byte[] bs = bi.toByteArray();// 该数组包含此 BigInteger 的二进制补码表示形式。
            byte[] originBs = new byte[bs.length - 1];
            byte[] target = bs;
            if (bs[0] == 0) {
                System.arraycopy(bs, 1, originBs, 0, originBs.length); // 去掉补码
                target = originBs;
            }
            // 创建密钥
            DESKeySpec desKeySpec = new DESKeySpec(SECRET_KEY.getBytes("UTF-8"));
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
            SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
            // 解密
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, secretKey);
            byte[] decryptionBs = cipher.doFinal(target);
            return new String(decryptionBs, "UTF-8");
        } catch (Exception ex) {
            //ex.printStackTrace();
            log.error("====exception, decryption failure, hex:" + hex);
        }
        return hex;
    }

    @Override
    public List<SerialVo> getSerialList(String contentId, String prdInfoId, String contentFrom) {
        StringBuffer sql = new StringBuffer();
        sql.append(" SELECT c.id,                                                                   ");
        sql.append("        c.content_id,                                                           ");
        sql.append("        c.name,                                                                 ");
        sql.append("        c.serial_content_id,                                                    ");
        sql.append("        c.serial_sequence,                                                      ");
        sql.append("        c.status,                                                               ");
        sql.append("        pc.prd_cont_id,                                                         ");
        sql.append("        pc.bc_status,                                                           ");
        sql.append("        pc.dist_status,                                                         ");
        sql.append("        pc.pub_status,                                                          ");
        sql.append("        pc.bc_refuse_reason,                                                    ");
        sql.append("        c.create_time,                                                    		");
        sql.append("        c.asset_id,                                                       		");
        sql.append("        pc.is_emergency,	                                                    ");
        sql.append("        pc.publish_no_voms_status,                                              ");
        sql.append("        c.cdn_status,                                                      		");
        sql.append("        c.gslb_status,                                                     		");
        sql.append("        c.movie_lib_id,                                                    		");
        sql.append("        c.cache_cdn_status,                                                     ");
        sql.append("        c.serial_trailing_sequence                                              ");
        sql.append("   FROM content c                                                               ");
        sql.append("   LEFT JOIN prd_cont pc on (c.content_id = pc.content_id and pc.is_delete = 0  ");
//		sql.append("  WHERE c.serial_content_id = ?	 and c.status != 2                              ");
        //开放媒资侧删除 剧集壳仍能查询到子集
        if (!StringUtils.isEmpty(prdInfoId)) {
            sql.append("  AND pc.prd_info_id  = ").append(prdInfoId);
        }
        sql.append(" )  WHERE 1=1 ");
        if (!StringUtils.isEmpty(contentId)) {
            sql.append(" and c.serial_content_id = " + contentId);
        }
        if (!StringUtils.isEmpty(contentFrom)) {
            sql.append(" and exists (select 1 from SECOND_CLASSIFY sc where sc.CONTENT_ID = pc.CONTENT_ID and " +
                    "sc.CLASSIFY_KEY = '内容形态' and sc.CLASSIFY_VALUE = '" + contentFrom + "' )");
        }
        sql.append("  ORDER BY to_number(c.serial_sequence) ASC, to_number(c.serial_trailing_sequence) ASC ");

        Query query = entityManager.createNativeQuery(sql.toString());
        List<Object[]> tmpList = query.getResultList();
        List<SerialVo> list = new ArrayList<SerialVo>();
        for (Object[] o : tmpList) {
            SerialVo sv = new SerialVo();
            sv.setId(StringUtil.null2Str(o[0]));
            sv.setContentId(StringUtil.null2Str(o[1]));
            sv.setName(StringUtil.null2Str(o[2]));
            sv.setSerialContentID(StringUtil.null2Str(o[3]));
            sv.setSerialSequence(StringUtil.null2Str(o[4]));
            sv.setStatus(StringUtil.null2Str(o[5]));
            sv.setPrdContId(StringUtil.null2Str(o[6]));
            sv.setBcStatus(StringUtil.null2Str(o[7]));
            sv.setDistStatus(StringUtil.null2Str(o[8]));
            sv.setPubStatus(StringUtil.null2Str(o[9]));
            sv.setBcRefuseReason(StringUtil.null2Str(o[10]));
            sv.setCreateTime(StringUtil.null2Str(o[11]));
            sv.setAssetId(StringUtil.null2Str(o[12]));
            sv.setIsEmergency(StringUtil.null2Str(o[13]));
            sv.setPublishNoVOMSStatus(StringUtil.null2Str(o[14]));
            sv.setCdnStatus(StringUtil.null2Str(o[15]));
            sv.setGslbStatus(StringUtil.null2Str(o[16]));
            sv.setMovieLibId(StringUtil.null2Str(o[17]));
            sv.setCacheCdnStatus(StringUtil.null2Str(o[18]));
            sv.setSerialTrailingSequence(StringUtil.null2Str(o[19]));
            list.add(sv);
        }
        return list;
    }

    List<PrdContVo> toPrdContVoList(List<Object[]> list) {
        List<PrdContVo> prdContVoList = new ArrayList<>();
        for (Object[] obj : list) {
            PrdContVo pc = new PrdContVo();
            pc.setPrdInfoId(StringUtil.null2Str(obj[0]));
            pc.setPrdInfoName(StringUtil.null2Str(obj[1]));
            pc.setPrdContId(StringUtil.nullToLong(obj[2]));
            pc.setContentId(StringUtil.nullToLong(obj[3]));
            pc.setContentName(StringUtil.null2Str(obj[4]));
            pc.setContentStatus(StringUtil.null2Str(obj[5]));
            pc.setBcStatus(StringUtil.null2Str(obj[6]));
            pc.setPublishNoVOMSStatus(StringUtil.null2Str(obj[7]));
            pc.setFormType(StringUtil.null2Str(obj[8]));
            pc.setEmergency(StringUtil.null2Str(obj[9]));
            pc.setOnTrial(StringUtil.null2Str(obj[10]));
            pc.setCopyrightType(StringUtil.null2Str(obj[11]));
            pc.setCreateTime(StringUtil.null2Str(obj[12]));
            pc.setCduration(StringUtil.null2Str(obj[13]));
            pc.setKeyWords(StringUtil.null2Str(obj[14]));
            pc.setFirstClassify(StringUtil.null2Str(obj[15]));
            pc.setAccessPlatFormType(StringUtil.null2Str(obj[16]));
            pc.setIsMultilingual(StringUtil.null2Str(obj[17]));
            pc.setCategory(StringUtil.null2Str(obj[18]));
            pc.setPrdContStatus(StringUtil.null2Str(obj[19]));
            prdContVoList.add(pc);
        }
        return prdContVoList;
    }


    public StringBuilder sqlStringWhere(boolean getCount, PrdContSelPojo prdContSelPojo, String sord, String sidx) {
        StringBuilder condition = new StringBuilder();
        if (getCount) {
            condition.append("select count(0) " +
                    "  from PRD_CONT pc, CONTENT c ,PRD_INFO pi  " +
                    "  where pc.CONTENT_ID = C.CONTENT_ID  and pi.PRDINFOID=pc.PRD_INFO_ID ");
        } else {
            condition.append("select pi.PRDINFOID prdInfoId,pi.NAME prdInfoName,pc.PRD_CONT_ID prdContId, pc.CONTENT_ID contentId, c.NAME contentName,c.STATUS contentStatus," +
                    " pc.BC_STATUS bcStatus,pc.PUBLISH_NO_VOMS_STATUS  publishNoVOMSStatus,c.FORM_TYPE formType,pc.IS_EMERGENCY emergency,pc.ONTRIAL onTrial," +
                    "c.COPYRIGHT_TYPE copyrightType,c.CREATE_TIME createTime,c.CDURATION cduration,c.KEY_WORDS  keywords,c.DISPLAY_TYPE firstClassify," +
                    "c.ACCESS_PLATFORM_TYPE accessPlatFormType,c.IS_MULTILIN_GUAL isMultilingual ,c.CATEGORY category,pc.IS_DELETE prdContStatus " +
                    "  from PRD_CONT pc, CONTENT c ,PRD_INFO pi  " +
                    "  where pc.CONTENT_ID = C.CONTENT_ID  and pi.PRDINFOID=pc.PRD_INFO_ID ");
        }
        if (prdContSelPojo != null) {
            if (StringUtils.isNotBlank(prdContSelPojo.getPrdInfoId())) {
                condition.append(" and pc.PRD_INFO_ID = " + prdContSelPojo.getPrdInfoId());
            }
            if (StringUtils.isNotBlank(prdContSelPojo.getProductInfoPackageId())) {
                condition.append(" and pi.product_info_package_id = " + prdContSelPojo.getProductInfoPackageId());
            }
            if (prdContSelPojo.getPrdContId() != null) {
                condition.append(" and pc.PRD_CONT_ID=" + prdContSelPojo.getPrdContId());
            }
            if (prdContSelPojo.getMmsID() != null) {
                condition.append(" and pc.MMS_ID =" + prdContSelPojo.getMmsID());
            }
            if (prdContSelPojo.getContentId() != null) {
                //condition.append(" and pc.CONTENT_ID=" + prdContSelPojo.getContentId());
                condition.append(" and (pc.CONTENT_ID = " + prdContSelPojo.getContentId() + " " +
                        "or pc.CONTENT_ID = (select cc.SERIAL_CONTENT_ID from content cc where cc.content_id=" + prdContSelPojo.getContentId() + "))");
            }
            if (StringUtils.isNotBlank(prdContSelPojo.getFirstClassify())) {
                condition.append(" and c.DISPLAY_TYPE='" + prdContSelPojo.getFirstClassify() + "'");
            }

            if (StringUtils.isNotBlank(prdContSelPojo.getDisplaySubSet())) {
                if ("0".equals(prdContSelPojo.getDisplaySubSet())) {
                    condition.append(" and c.form_type != '7'");
                }
            }

            //6:剧集壳 1:显示子集
            if (StringUtils.isNotBlank(prdContSelPojo.getFormType())) {
                if ("6".equals(StringUtil.null2Str(prdContSelPojo.getFormType()))
                        && "1".equals(StringUtil.null2Str(prdContSelPojo.getDisplaySubSet()))) {
                    condition.append(" and c.form_type in ('6', '7') ");
                } else {
                    condition.append(" and c.form_type = " + prdContSelPojo.getFormType());
                }
            }
            //未选剧集类型的 1:显示子集
			/* if (StringUtils.isBlank(prdContSelPojo.getFormType()) &&"1".equals(StringUtil.null2Str(prdContSelPojo.getDisplaySubSet()))) {
				condition.append(" and c.form_type = '7' ");
			} */

            //1:屏蔽
            if ("1".equals(StringUtil.null2Str(prdContSelPojo.getShieldDelCont()))) {
                condition.append(" and c.status  in (0, 1, 3)");
                condition.append(" and pc.IS_DELETE  = 0 and  pc.FILE_ACTION <> 2");
            }

            if (StringUtils.isNotBlank(prdContSelPojo.getPublishNoVOMSStatus())) {
                condition.append(" and pc.PUBLISH_NO_VOMS_STATUS='" + prdContSelPojo.getPublishNoVOMSStatus() + "'");
            }
            if (StringUtils.isNotBlank(prdContSelPojo.getBcStatus())) {
                condition.append(" and pc.BC_STATUS='" + prdContSelPojo.getBcStatus() + "'");
            }
            if (StringUtils.isNotBlank(prdContSelPojo.getAccessPlatFormType())) {
                condition.append(" and c.ACCESS_PLATFORM_TYPE='" + prdContSelPojo.getAccessPlatFormType() + "'");
            }
            //促销类型
            if (!StringUtil.isNullStr(prdContSelPojo.getSalCategory())) {
                condition.append(" AND exists (select 1 from CONTENT_FEE cf where cf.SALE_CATEGORY = " + prdContSelPojo.getSalCategory() + " and (pc.PRD_CONT_ID = cf.POMS_ID or pc.PRD_INFO_ID = cf.POMS_ID) ) ");
            }
            if (StringUtils.isNotBlank(prdContSelPojo.getCategory())) {
                condition.append(" and c.CATEGORY='" + prdContSelPojo.getCategory() + "'");
            }
            if (StringUtils.isNotBlank(prdContSelPojo.getContentFrom())) {
                condition.append(" and exists (select 1 from SECOND_CLASSIFY sc where sc.CONTENT_ID = pc.CONTENT_ID and " +
                        "sc.CLASSIFY_KEY like '%内容形态%' and sc.CLASSIFY_VALUE like '%" + prdContSelPojo.getContentFrom() + "%')");
            }
            if (StringUtils.isNotBlank(prdContSelPojo.getLastModifyTimeBegin())) {
                //兼容生产有14位的日期
                condition.append(" and decode(lengthb(c.LAST_MODIFY_TIME),19,TO_DATE(c.LAST_MODIFY_TIME,'yyyy-MM-dd HH24:mi:ss'),TO_DATE(c.LAST_MODIFY_TIME,'yyyyMMddHH24miss')) >  TO_DATE('" + prdContSelPojo.getLastModifyTimeBegin() + "', 'yyyy-MM-dd HH24:mi:ss')");
            }
            if (StringUtils.isNotBlank(prdContSelPojo.getLastModifyTimeEnd())) {
                condition.append(" and decode(lengthb(c.LAST_MODIFY_TIME),19,TO_DATE(c.LAST_MODIFY_TIME,'yyyy-MM-dd HH24:mi:ss'),TO_DATE(c.LAST_MODIFY_TIME,'yyyyMMddHH24miss'))  <=  TO_DATE('" + prdContSelPojo.getLastModifyTimeEnd() + "', 'yyyy-MM-dd HH24:mi:ss')+1");
            }
            if (StringUtils.isNotBlank(prdContSelPojo.getCreateTimeBegin())) {
                condition.append(" and decode(lengthb(c.CREATE_TIME),19,TO_DATE(c.CREATE_TIME,'yyyy-MM-dd HH24:mi:ss'),TO_DATE(c.CREATE_TIME,'yyyyMMddHH24miss'))  >  TO_DATE('" + prdContSelPojo.getCreateTimeBegin() + "', 'yyyy-MM-dd HH24:mi:ss')");
            }
            if (StringUtils.isNotBlank(prdContSelPojo.getCreateTimeEnd())) {
                condition.append(" and decode(lengthb(c.CREATE_TIME),19,TO_DATE(c.CREATE_TIME,'yyyy-MM-dd HH24:mi:ss'),TO_DATE(c.CREATE_TIME,'yyyyMMddHH24miss'))  <=  TO_DATE('" + prdContSelPojo.getCreateTimeEnd() + "', 'yyyy-MM-dd HH24:mi:ss')+1");
            }
            if (prdContSelPojo.getProductId() != null) {
                condition.append(" and pc.PRODUCT_ID like '%" + prdContSelPojo.getProductId() + "%'");
            }
            if (StringUtils.isNotBlank(prdContSelPojo.getContentName())) {
                condition.append(" and c.name like '%" + prdContSelPojo.getContentName() + "%'");
            }
            if (StringUtils.isNotBlank(prdContSelPojo.getAuthor())) {
                condition.append(" and c.author like '%" + prdContSelPojo.getAuthor() + "%'");
            }
            if (StringUtils.isNotBlank(prdContSelPojo.getAssist())) {
                String[] keyS = prdContSelPojo.getAssist().split(",");
                if (keyS.length == 1) {
                    condition.append(" and c.assist like '%" + prdContSelPojo.getAssist() + "%'");
                } else {
                    for (int i = 0; i < keyS.length; i++) {
                        if (i == 0) {
                            condition.append(" and( c.assist like '%" + keyS[i] + "%'");
                        } else if (i == keyS.length - 1) {
                            condition.append(" or c.assist like '%" + keyS[i] + "%' )");
                        } else {
                            condition.append(" or c.assist like '%" + keyS[i] + "%'");
                        }
                    }
                }
            }
            if (StringUtils.isNotBlank(prdContSelPojo.getRecommendation())) {
                condition.append(" and c.RECOMMENDATION like '%" + prdContSelPojo.getRecommendation() + "%'");
            }
            if (StringUtils.isNotBlank(prdContSelPojo.getKeyWords())) {
                String[] keyS = prdContSelPojo.getKeyWords().split(",");
                for (int i = 0; i < keyS.length; i++) {
                    if (i == 0) {
                        condition.append(" and c.KEY_WORDS like '%" + keyS[i] + "%'");
                        condition.append(" or c.PRIMARY_KEY_WORD like '%" + keyS[i] + "%'");
                    } else {
                        condition.append(" or c.KEY_WORDS like '%" + keyS[i] + "%'");
                        condition.append(" or c.PRIMARY_KEY_WORD like '%" + keyS[i] + "%'");
                    }
                }
            }
        }
        if (StringUtils.isNotBlank((sidx))) {
            condition.append(" order by " + sidx);
            if ("desc".equals(sord.toLowerCase())) {
                condition.append(" desc");
            }
        }
        log.info("产品展现节目搜索sql：" + condition);
        return condition;
    }

    public List exportQuerySql(String sql, Object[] parms, int start, int limit) {
        Query query = entityManager.createNativeQuery(sql);
        for (int i = 0; i < parms.length; i++) {
            query.setParameter(i, parms[i]);
        }
        query.setFirstResult(start > 0 ? start : 0);
        query.setMaxResults(limit > 0 ? limit : 2000);
        return query.getResultList();
    }

    public List querySql(String sql, Object[] parms, int start, int limit) {
        Query query = entityManager.createNativeQuery(sql);
        for (int i = 0; i < parms.length; ++i) {
            query.setParameter(i, parms[i]);
        }

        query.setFirstResult(start > 0 ? start : 0);
        query.setMaxResults(limit > 0 && limit < 2000 ? limit : 2000);
        return query.getResultList();
    }

    public List querySql(String sql, Object[] parms) {
        Query query = entityManager.createNativeQuery(sql);
        for (int i = 0; i < parms.length; ++i) {
            query.setParameter(i, parms[i]);
        }
        return query.getResultList();
    }
}
